package com.guadou.lib_baselib.base.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.base.fragment.AbsVMFragment
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.util.NetWorkUtil

/**
 * 加入ViewModel与LoadState
 * 默认为Loading的加载
 */
abstract class BaseVMFragment<VM : BaseViewModel> : AbsVMFragment<VM>() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //观察网络数据状态
        viewModel.getActionLiveData().observe(viewLifecycleOwner, stateObserver)

        initData()
        startObserve()
    }

    override fun setContentView(inflater: LayoutInflater, container: ViewGroup?): View {
        return layoutInflater.inflate(getLayoutIdRes(), container, false)
    }

    /**
     * 获取layout的id，具体由子类实现
     */
    abstract fun getLayoutIdRes(): Int
    abstract fun startObserve()
    abstract fun initData()

    override fun onNetworkConnectionChanged(
        isConnected: Boolean,
        networkType: NetWorkUtil.NetworkType?
    ) {
    }

    // ================== 网络状态的监听 ======================

    private var stateObserver: Observer<LoadAction> = Observer { loadAction ->
        if (loadAction != null) {

            when (loadAction.action) {
                LoadAction.STATE_NORMAL -> showStateNormal()
                LoadAction.STATE_ERROR -> showStateError(loadAction.message)
                LoadAction.STATE_SUCCESS -> showStateSuccess()
                LoadAction.STATE_LOADING -> showStateLoading()
                LoadAction.STATE_NO_DATA -> showStateNoData()
                LoadAction.STATE_PROGRESS -> showStateProgress()
                LoadAction.STATE_HIDE_PROGRESS -> hideStateProgress()
            }

        }
    }

    protected fun showStateNormal() {}

    protected fun showStateError(message: String?) {
        LoadingDialogManager.get().dismissLoading()
    }

    protected fun showStateSuccess() {
        LoadingDialogManager.get().dismissLoading()
    }

    protected fun showStateLoading() {
        LoadingDialogManager.get().showLoading(mActivity)
    }

    protected fun showStateNoData() {
        LoadingDialogManager.get().dismissLoading()
    }

    protected fun showStateProgress() {
        LoadingDialogManager.get().showLoading(mActivity)
    }

    protected fun hideStateProgress() {
        LoadingDialogManager.get().dismissLoading()
    }

}